<?php

namespace app\adminapi\controller;

use app\model\UsersModel;
use app\model\OperationLogModel;
use app\model\AdminsModel;
use support\Db;
use Webman\Http\Request;

class Dashboard extends BaseAdminApi
{
    /**
     * 不需要登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 不需要权限验证的方法（已登录但不验证具体权限）
     * @var array
     */
    protected $noNeedPermission = ['getStatistics', 'getRecentLogs', 'getUserGrowth', 'getSystemInfo'];

    /**
     * 获取仪表盘统计数据
     */
    public function getStatistics(Request $request)
    {
        try {
            // 用户统计
            $totalUsers = UsersModel::count();
            $todayUsers = UsersModel::whereDate('created_at', date('Y-m-d'))->count();
            $activeUsers = UsersModel::where('status', 1)->count();
            $weekUsers = UsersModel::whereBetween('created_at', [
                date('Y-m-d', strtotime('-7 days')),
                date('Y-m-d')
            ])->count();

            // 管理员统计
            $totalAdmins = AdminsModel::count();
            $activeAdmins = AdminsModel::where('status', 1)->count();

            // 操作日志统计
            $totalLogs = OperationLogModel::count();
            $todayLogs = OperationLogModel::whereDate('created_at', date('Y-m-d'))->count();
            $successLogs = OperationLogModel::where('is_success', 1)->count();
            $errorLogs = OperationLogModel::where('is_success', 0)->count();

            // 计算增长率
            $yesterdayUsers = UsersModel::whereDate('created_at', date('Y-m-d', strtotime('-1 day')))->count();
            $userGrowthRate = $yesterdayUsers > 0 ? round((($todayUsers - $yesterdayUsers) / $yesterdayUsers) * 100, 2) : 0;

            $yesterdayLogs = OperationLogModel::whereDate('created_at', date('Y-m-d', strtotime('-1 day')))->count();
            $logGrowthRate = $yesterdayLogs > 0 ? round((($todayLogs - $yesterdayLogs) / $yesterdayLogs) * 100, 2) : 0;

            $data = [
                'users' => [
                    'total' => $totalUsers,
                    'today' => $todayUsers,
                    'active' => $activeUsers,
                    'week' => $weekUsers,
                    'growth_rate' => $userGrowthRate
                ],
                'admins' => [
                    'total' => $totalAdmins,
                    'active' => $activeAdmins
                ],
                'logs' => [
                    'total' => $totalLogs,
                    'today' => $todayLogs,
                    'success' => $successLogs,
                    'error' => $errorLogs,
                    'success_rate' => $totalLogs > 0 ? round(($successLogs / $totalLogs) * 100, 2) : 0,
                    'growth_rate' => $logGrowthRate
                ]
            ];

            return data($data);
        } catch (\Exception $e) {
            return fail('获取统计数据失败：' . $e->getMessage());
        }
    }

    /**
     * 获取最近操作日志
     */
    public function getRecentLogs(Request $request)
    {
        try {
            $params = $request->get();
            $limit = $params['limit'] ?? 10;

            $logs = OperationLogModel::with(['admin', 'user'])
                ->orderBy('created_at', 'desc')
                ->limit($limit)
                ->get()
                ->map(function ($log) {
                    return [
                        'id' => $log->id,
                        'method' => $log->method,
                        'uri' => $log->uri,
                        'description' => $log->description,
                        'is_success' => $log->is_success,
                        'response_code' => $log->response_code,
                        'duration' => $log->duration,
                        'ip' => $log->ip,
                        'operator_name' => $log->operator_name,
                        'user_type' => $log->user_type,
                        'created_at' => $log->created_at->format('Y-m-d H:i:s')
                    ];
                });

            return data($logs);
        } catch (\Exception $e) {
            return fail('获取操作日志失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户增长趋势（最近7天）
     */
    public function getUserGrowth(Request $request)
    {
        try {
            $data = [];
            
            for ($i = 6; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-{$i} days"));
                $count = UsersModel::whereDate('created_at', $date)->count();
                
                $data[] = [
                    'date' => $date,
                    'count' => $count,
                    'label' => date('m-d', strtotime($date))
                ];
            }

            return data($data);
        } catch (\Exception $e) {
            return fail('获取用户增长趋势失败：' . $e->getMessage());
        }
    }

    /**
     * 获取系统信息
     */
    public function getSystemInfo(Request $request)
    {
        try {
            $data = [
                'php_version' => PHP_VERSION,
                'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
                'memory_usage' => round(memory_get_usage() / 1024 / 1024, 2) . ' MB',
                'memory_peak' => round(memory_get_peak_usage() / 1024 / 1024, 2) . ' MB',
                'server_time' => date('Y-m-d H:i:s'),
                'timezone' => date_default_timezone_get(),
                'disk_free' => function_exists('disk_free_space') ? round(disk_free_space('.') / 1024 / 1024 / 1024, 2) . ' GB' : 'Unknown',
                'disk_total' => function_exists('disk_total_space') ? round(disk_total_space('.') / 1024 / 1024 / 1024, 2) . ' GB' : 'Unknown'
            ];

            return data($data);
        } catch (\Exception $e) {
            return fail('获取系统信息失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户分布统计（按登录类型）
     */
    public function getUserDistribution(Request $request)
    {
        try {
            $distribution = UsersModel::select('login_type', Db::raw('count(*) as count'))
                ->groupBy('login_type')
                ->get()
                ->map(function ($item) {
                    $typeMap = [
                        'username' => '用户名登录',
                        'wechat' => '微信登录',
                        'wechat_mp' => '微信小程序'
                    ];
                    
                    return [
                        'type' => $item->login_type,
                        'name' => $typeMap[$item->login_type] ?? $item->login_type,
                        'count' => $item->count
                    ];
                });

            return data($distribution);
        } catch (\Exception $e) {
            return fail('获取用户分布失败：' . $e->getMessage());
        }
    }
}